
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dexie.js 示例</title>
    <script src="dexie.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        .section {
            border: 1px solid #ddd;
            padding: 15px;
            border-radius: 5px;
        }
        button {
            padding: 8px 12px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }

        input
        {
            min-height: 25px;
            border: 1px solid darkgreen;
            outline: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Dexie.js 示例</h1>
        
        <div class="section">
            <h2>数据库操作</h2>
            <button id="initDb">初始化数据库</button>
            <button id="clearDb">清空数据库</button>
            <div id="dbStatus"></div>
        </div>
        
        <div class="section">
            <h2>添加数据</h2>
            <div>
                <input type="text" id="nameInput" placeholder="姓名">
                <input type="text" id="ageInput"  placeholder="年龄">
                <button id="addBtn">添加</button>
            </div>
        </div>
        
        <div class="section">
            <h2>查询数据</h2>
            <button id="queryAllBtn">查询所有</button>
            <button id="queryYoungBtn">查询年龄小于30</button>
            <div id="queryResults"></div>
        </div>
        
        <div class="section">
            <h2>数据表</h2>
            <table id="dataTable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>姓名</th>
                        <th>年龄</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="tableBody"></tbody>
            </table>
        </div>
    </div>

    <script>
        // 定义数据库
        const db = new Dexie("FriendsDatabase");
        
        // 定义数据库模式和版本
        db.version(1).stores({
            friends: "++id, name, age" // 主键是自增的id
        });
        
        // 初始化数据库按钮
        document.getElementById("initDb").addEventListener("click", async () => {
            try {
                await db.open();
                document.getElementById("dbStatus").textContent = "数据库已初始化";
                console.log("数据库已打开");
            } catch (error) {
                document.getElementById("dbStatus").textContent = "初始化失败: " + error;
                console.error("初始化失败:", error);
            }
        });
        
        // 清空数据库按钮
        document.getElementById("clearDb").addEventListener("click", async () => {
            try {
                await db.friends.clear();
                document.getElementById("dbStatus").textContent = "数据库已清空";
                refreshTable();
            } catch (error) {
                document.getElementById("dbStatus").textContent = "清空失败: " + error;
                console.error("清空失败:", error);
            }
        });
        
        // 添加数据按钮
        document.getElementById("addBtn").addEventListener("click", async () => {
            const name = document.getElementById("nameInput").value;
            const age = parseInt(document.getElementById("ageInput").value);
            
            if (!name || isNaN(age)) {
                alert("请输入有效的姓名和年龄");
                return;
            }
            
            try {
                const id = await db.friends.add({ name, age });
                document.getElementById("dbStatus").textContent = `添加成功，ID: ${id}`;
                document.getElementById("nameInput").value = "";
                document.getElementById("ageInput").value = "";
                refreshTable();
            } catch (error) {
                document.getElementById("dbStatus").textContent = "添加失败: " + error;
                console.error("添加失败:", error);
            }
        });
        
        // 查询所有数据按钮
        document.getElementById("queryAllBtn").addEventListener("click", async () => {
            try {
                const friends = await db.friends.toArray();
                displayResults(friends);
            } catch (error) {
                document.getElementById("queryResults").textContent = "查询失败: " + error;
                console.error("查询失败:", error);
            }
        });
        
        // 查询年龄小于30按钮
        document.getElementById("queryYoungBtn").addEventListener("click", async () => {
            try {
                const youngFriends = await db.friends
                    .where("age")
                    .below(30)
                    .toArray();
                displayResults(youngFriends);
            } catch (error) {
                document.getElementById("queryResults").textContent = "查询失败: " + error;
                console.error("查询失败:", error);
            }
        });
        
        // 显示查询结果
        function displayResults(results) {
            const resultsDiv = document.getElementById("queryResults");
            if (results.length === 0) {
                resultsDiv.innerHTML = "<p>没有找到数据</p>";
                return;
            }
            
            let html = "<ul>";
            results.forEach(friend => {
                html += `<li>${friend.name}, ${friend.age}岁 (ID: ${friend.id})</li>`;
            });
            html += "</ul>";
            resultsDiv.innerHTML = html;
        }
        
        // 刷新表格数据
        async function refreshTable() {
            const tbody = document.getElementById("tableBody");
            tbody.innerHTML = "";
            
            try {
                const friends = await db.friends.toArray();
                
                friends.forEach(friend => {
                    const row = document.createElement("tr");
                    row.innerHTML = `
                        <td>${friend.id}</td>
                        <td>${friend.name}</td>
                        <td>${friend.age}</td>
                        <td>
                            <button onclick="deleteFriend(${friend.id})">删除</button>
                            <button onclick="updateFriend(${friend.id})">更新</button>
                        </td>
                    `;
                    tbody.appendChild(row);
                });
            } catch (error) {
                console.error("刷新表格失败:", error);
            }
        }
        
        // 删除朋友
        window.deleteFriend = async function(id) {
            try {
                await db.friends.delete(id);
                refreshTable();
                document.getElementById("dbStatus").textContent = `ID ${id} 已删除`;
            } catch (error) {
                document.getElementById("dbStatus").textContent = "删除失败: " + error;
                console.error("删除失败:", error);
            }
        };
        
        // 更新朋友信息
        window.updateFriend = async function(id) {
            const newName = prompt("输入新的姓名:");
            const newAge = parseInt(prompt("输入新的年龄:"));
            
            if (!newName || isNaN(newAge)) {
                alert("请输入有效的姓名和年龄");
                return;
            }
            
            try {
                await db.friends.update(id, { name: newName, age: newAge });
                refreshTable();
                document.getElementById("dbStatus").textContent = `ID ${id} 已更新`;
            } catch (error) {
                document.getElementById("dbStatus").textContent = "更新失败: " + error;
                console.error("更新失败:", error);
            }
        };
        
        // 初始化时打开数据库
        db.open().catch(err => {
            console.error("打开数据库失败:", err);
            document.getElementById("dbStatus").textContent = "打开数据库失败: " + err;
        });
    </script>
</body>
</html>
